{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Min Stack（最小栈）\n",
    "\n",
    "[@mjd507](https://github.com/mjd507)\n",
    "\n",
    "![Logo](DP-69.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Design a simple stack that supports push, pop, top, and retrieving the minimum element in constant time.\n",
    "\n",
    "- `push(x)` - Push element x onto stack.\n",
    "- `pop()` - Removes the element on top of the stack.\n",
    "- `top()` - Get the top element.\n",
    "- `getMin()` - Retrieve the minimum element in the stack.\n",
    "\n",
    "**Note: be sure that `pop()` and `top()` handle being called on an empty stack.**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;设计一个简单的栈，支持压入、弹出、取栈顶和在$O(1)$时间内获取栈内最小元素。\n",
    "\n",
    "- `push(x)` - 将元素$x$压栈\n",
    "- `pop()` - 使栈顶元素出栈\n",
    "- `top()` - 取栈顶元素\n",
    "- `getMin()` - 获取栈内最小元素\n",
    "\n",
    "&emsp;&emsp;**注意：确保`pop()`和`top()`能够解决在栈空时被调用的情况。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MinStack(object):\n",
    "    def __init__(self):\n",
    "        self.stack = []\n",
    "\n",
    "    def push(self, x: int):\n",
    "        self.stack.append({\n",
    "            'value': x,\n",
    "            'min': min(x, self.getMin())\n",
    "        })\n",
    "\n",
    "    def pop(self) -> int:\n",
    "        if self.stack == []:\n",
    "            return None\n",
    "        else:\n",
    "            return self.stack.pop()['value']\n",
    "\n",
    "    def top(self) -> int:\n",
    "        if self.stack == []:\n",
    "            return None\n",
    "        else:\n",
    "            return self.stack[-1]['value']\n",
    "\n",
    "    def getMin(self) -> int:\n",
    "        if self.stack == []:\n",
    "            return float('inf')\n",
    "        else:\n",
    "            return self.stack[-1]['min']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-3\n",
      "0\n",
      "-2\n"
     ]
    }
   ],
   "source": [
    "x = MinStack()\n",
    "x.push(-2)\n",
    "x.push(0)\n",
    "x.push(-3)\n",
    "print(x.getMin())\n",
    "x.pop()\n",
    "print(x.top())\n",
    "print(x.getMin())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
